package com.hr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.Dictionary;
import com.espirit.eap.manager.DictionaryService;
import com.espirit.eap.manager.SysSettingServiceSupport;
import com.espirit.finance.core.AcctTerm;
import com.espirit.finance.core.AcctTermService;
import com.googlecode.cswish.annotation.GenericType;
import com.googlecode.cswish.struts.spring.CacheService;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
public class HrSettingService extends SysSettingServiceSupport{
	@Resource
	GenericService genericService;
	
	@Resource
	AcctTermService acctTermService;
	
	@Resource
	DictionaryService dictionaryService;
	
	@Resource
	private CacheService cacheService;
	
	private HrSetting hrSetting = new HrSetting();
	
	static final String PREFIX = "hr.";
	static final String PREFIX_LEAVE = "l";
	
	@PostConstruct
	public void init(){
		initValues();
	}
	
	public void initValues(){
		reSet(hrSetting);
	}
	
	public HrSetting getHrSetting(){
		return hrSetting;
	}
	
	public  HrSettingService() {
		
	}
	
	public List<Map<String,String>> getSrcLeaveTypes(){
		List<Dictionary> results = dictionaryService.getDictionariesByType(LeaveAppItem.LEAVE_TYPE);
		if (results == null) return null;
		
		List<Map<String,String>> leaveTypes  = new ArrayList();
		for(Dictionary dict : results){
			Map<String, String > values = new HashMap<String, String>();
			values.put("id", PREFIX_LEAVE + dict.getValue());
			values.put("name", dict.getName());
			leaveTypes.add(values);
		}
		return leaveTypes;
	}
	
	@Override
	public void update(@GenericType Object model) {
		super.update(model);
		AcctTerm maxTerm = acctTermService.getMaxAcctTerm();
		if (maxTerm.equals(hrSetting.getCurrentAcctTerm())){
			acctTermService.generateNext(hrSetting.getCurrentAcctTerm());
		}
	}
	
	@Override
	public String getPrefix() {
		return PREFIX;
	}
	
	public Integer[] getPaidLeaves(){
		String leaves = getHrSetting().getPaidLeaves();
		if (StringUtils.isEmpty(leaves)) return null;
		String[]  strLeaves = leaves.split(",");
		int length = strLeaves.length;
		Integer[] result = new Integer[length];
		for(int i = 0 ; i < length ; i++){
			String temp = strLeaves[i].trim();
			result[i] = Integer.valueOf(temp.substring(PREFIX_LEAVE.length()));
		}
		return result;
	}
}
